package httplib;

import android.util.Log;

import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;

import java.io.UnsupportedEncodingException;
import java.util.Map;

/**
 * Created by niraymond on 16/8/22.
 */
public class VolleyRequest<T> extends Request<T> {
    private final Gson gson = new Gson();
    private final Class<T> clazz;
    private final Map<String, String> headers;
    private final Response.Listener<T> listener;
    private final Map<String, String> postBody;

    /**
     * Make a GET request and return a parsed object from JSON.
     *
     * @param url URL of the request to make
     * @param clazz Relevant class object, for Gson's reflection
     * @param headers Map of request headers
     */
    public VolleyRequest(String url, Class<T> clazz, Map<String, String> headers,
                         Map<String, String> postBody,
                         Response.Listener<T> listener, Response.ErrorListener errorListener) {
        super(Method.POST, url, errorListener);
        this.clazz = clazz;

        this.headers = headers;
        this.listener = listener;
        this.postBody = postBody;
    }


    @Override
    protected Map<String, String> getParams() throws AuthFailureError {
        Log.e("Raymond Tag", postBody.toString());
        return postBody;
    }

    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        return headers != null ? headers : super.getHeaders();
    }

    @Override
    protected void deliverResponse(T response) {
        listener.onResponse(response);
    }

    @Override
    protected Response<T> parseNetworkResponse(NetworkResponse response) {
        String json = "";
        try {
            Log.e("Raymond Tag", new String(response.data, "utf-8"));


            json = new String(
                    response.data,
                    HttpHeaderParser.parseCharset(response.headers));
            BaseResponse resp = gson.fromJson(json, BaseResponse.class);
            if(resp.getRsp().equalsIgnoreCase("succ")){
                return Response.success(
                        gson.fromJson(resp.getData(), clazz),
                        HttpHeaderParser.parseCacheHeaders(response));
            }else{
                return Response.error(new VolleyError(resp.getData().toString()));
            }


        } catch (UnsupportedEncodingException e) {
            return Response.error(new VolleyError("服务返回不支持的编码格式, Json : "+json + ". 异常:" + e.getMessage()));
        } catch (JsonSyntaxException e) {
            return Response.error(new VolleyError("数据解析错误,Json"+json + ". 异常:" + e.getMessage()));
        }
    }
}
